<template>
  <van-nav-bar title="修改地址" left-text="返回" left-arrow @click-left="goBack" />
  <van-address-edit
    :area-list="areaList"
    show-set-default
    show-delete
    :address-info="info"
    @save="onSave"
    @delete="onDelete"
  />
</template>
<script setup>
import { areaList } from "@vant/area-data";
const { cookies } = useCookies();
const router = useRouter();
const route = useRoute();
const LoginUser = reactive(cookies.get("LoginUser"));
const id = ref(0);
const info = ref({});
onMounted(() => {
  id.value = route.query.id ? route.query.id : 0;
  getInfoData();
});

const goBack = () => {
  router.go(-1);
};

const getInfoData = async () => {
  let data = {
    id: id.value,
    busid: LoginUser.id,
  };
  let result = await Api.addressInfo(data);
  if (result.code == 1) {
    let data = result.data;
    info.value = {
      name: data.consignee,
      tel: data.mobile,
      areaCode: data.district,
      addressDetail: data.address,
      isDefault: data.status == "1" ? true : false,
    };
  }
};

const onSave = async (val) => {
  let data = {
    id: id.value,
    busid: LoginUser.id,
    consignee: val.name,
    code: val.areaCode,
    address: val.addressDetail,
    mobile: val.tel,
    status: val.isDefault == true ? "1" : "0",
  };
  let result = await Api.addressEdit(data);
  if (result.code == 1) {
    showNotify({
      type: "success",
      message: result.msg,
      onClose: () => {
        goBack();
      },
    });
  } else {
    showNotify({ type: "danger", message: result.msg });
  }
};

const onDelete = () => {
  showConfirmDialog({
    title: "删除",
    message: "确认是否删除当前收货地址？",
  })
    .then(async () => {
      let result = await Api.addressDel({ id: id.value, busid: LoginUser.id });
      if (result.code == 1) {
        showNotify({
          type: "success",
          message: result.msg,
          onClose: () => {
            goBack();
          },
        });
      } else {
        showNotify({ type: "danger", message: result.msg });
      }
    })
    .catch(() => {});
};
</script>
